package com.baidu.util.time.nlp.festival.strategy;

import com.baidu.util.time.nlp.festival.FestivalDayInfo;
import com.baidu.util.time.util.DateUtil;
import org.joda.time.DateTime;

/**
 * 第几周的第几天处理
 */
public class DayOfWeekFestivalDayStrategy implements FestivalDayStrategy {
    private boolean isAutoPlusYear = false;

    @Override
    public DateTime getDateTime(String text, DateTime baseTime, FestivalDayInfo info) {
        if (text.indexOf(info.getName()) == -1) {
            return null;
        }
        if (baseTime == null) {
            isAutoPlusYear = true;
            baseTime = DateTime.now();
        }

        DateTime festivalDay = calcFestivalDay(baseTime, info);

        if (isAutoPlusYear && baseTime.isAfter(festivalDay)) {
            festivalDay = calcFestivalDay(baseTime.plusYears(1), info);
        }
        return festivalDay;
    }

    private DateTime calcFestivalDay(DateTime baseTime, FestivalDayInfo info) {
        String[] dateArray = info.getDateString().split("&");
        int month = Integer.parseInt(dateArray[0]);
        int numOfWeek = Integer.parseInt(dateArray[1]);
        int weekDay = Integer.parseInt(dateArray[2]);
        int offDay = 6;
        if (weekDay > 5) {
            offDay = 1;
        }

        DateTime festivalDay = baseTime
                .withMonthOfYear(month)
                .dayOfMonth().withMinimumValue()
                .plusDays(offDay)
                .dayOfWeek().setCopy(weekDay)
                .plusWeeks(numOfWeek - 1);
        return DateUtil.setDefaultTime(festivalDay);
    }
}
